package cn.aylog.config;

import cn.aylog.pojo.Animal;
import cn.aylog.pojo.Pet;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 增加返回值转换器
        converters.add(new MyHttpMessageConverter());
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 增加格式解析器
        registry.addConverter(new Converter<String, Pet>() {
            @Override
            public Pet convert(String source) {
                String[] split = source.split(",");
                Pet pet = new Pet();
                pet.setName(split[0]);
                pet.setAge(Integer.parseInt(split[1]));
                return pet;
            }
        });
    }
}

class MyHttpMessageConverter implements HttpMessageConverter<Animal> {
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return true;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return clazz == Animal.class;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return new LinkedList<>(MediaType.parseMediaTypes("application/x-aylog"));
    }

    @Override
    public Animal read(Class<? extends Animal> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(Animal animal, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // ...
        Map<String, Object> map = new HashMap<>();
        map.put("name", animal.getName());
        map.put("age", animal.getAge());
        Pet pet = animal.getPet();
        map.put("pet", pet.getName() + "," + pet.getAge());
        System.out.println(map.toString());
        outputMessage.getBody().write(map.toString().getBytes());
    }
}